import { defineStore } from 'pinia';
import { getCache, setCache, removeCache } from '@/utils/cache';
import { logout as fetchLogout, login as fetchLogin } from '@/api/auth';

export const useAuthStore = defineStore('user', {
  state: () => {
    return {
      userInfo: getCache('userinfo'),
      token: getCache('token') || '',
    }
  },
  getters: {
		// 用户信息
		userInfo: (state) => {
			return state.userInfo;
		},
    // 是否登录
    isLogin: (state) => {
      return Boolean(state.token);
    },
		getToken: (state) => {
			return state.token ? state.token : '';
		},
  },
  actions: {
    /* 登录退出，重置用户信息等 */
    async logout() {
			try {
					const res = await fetchLogout();
					this.clearAuthStorage();
					return Promise.resolve(res);
			} catch (err) {
					return Promise.reject(err);
			}
		},
    clearAuthStorage() {
      removeCache('token')
      removeCache('userinfo')
    },

    /* 用户登录 */
    async login(username, password) {
      try {
        const { res } = await fetchLogin({ username, password });
				console.log(res)
				// if(res.code === 1){
				// 	await this.handleLoginInfo(res.data)
				// }
				return Promise.resolve(res);
      }
      catch (e) {
        console.warn('[Login Error]:', e)
				return Promise.reject(e);
      }
    },

    /* 处理登录返回的数据 */
    async handleLoginInfo(data) {
      // 将token和userInfo保存下来
			setCache('token', data.token)
			setCache('userinfo', data)
    },
  }
})